package net.dgg.rz.api.production.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.models.auth.In;
import net.dgg.commons.qds.model.LoginUser;
import net.dgg.framework.tac.utils.DggValidateUtil;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.service.ScGeneralService;
import net.dgg.iboss.base.service.UcApiService;
import net.dgg.iboss.base.util.DateUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.iboss.base.util.http.HttpUtility;
import net.dgg.rz.common.base.service.BaseService;
import net.dgg.rz.common.constant.MsgConstant;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.constant.SystemCommonConstant;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.service.CommonMangerExtService;
import net.dgg.rz.common.service.CommonService;
import net.dgg.rz.common.systemRecord.entity.SystemRecord;
import net.dgg.rz.common.systemRecord.service.SystemRecordService;
import net.dgg.rz.common.utils.DateUtils;
import net.dgg.rz.common.utils.InitComponent;
import net.dgg.rz.common.utils.ValidateUtils;
import net.dgg.rz.production.dao.*;
import net.dgg.rz.production.entity.*;
import net.dgg.rz.production.entity.dto.ProductOrderDto;
import net.dgg.rz.production.entity.dto.ScOrderAndTaskDTO;
import net.dgg.rz.production.entity.dto.TaskOperateRecordDTO;
import net.dgg.starter.call.GateWayClientUtils;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>@Title 生产部分对外接口service</p>
 * <p>@Description 办理中Service</p>
 * <p>@Version 1.0.0 版本号</p>
 * <p>@author maoquanyi</p>
 * <p>@date 2018年08月13日</p>
 * <p>Copyright © dgg group.All Rights Reserved. 版权信息</p>
 */
@Service
public class ApiProductionService extends BaseService {

    @Autowired
    private DesUtil desUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderJsonDao orderJsonDao;
    @Autowired
    private ProductNodeDao productNodeDao;
    @Autowired
    private OrderContactDao orderContactDao;
    @Autowired
    private OrderCustomerDao orderCustomerDao;
    @Autowired
    private OrderSubjectDao orderSubjectDao;
    @Autowired
    private ProductOrderDao productOrderDao;
    @Autowired
    private ProductTimeStatusDao productTimeStatusDao;
    @Autowired
    private ScGeneralService scGeneralService;

    @Autowired
    private CmsService cmsService;
    @Autowired
    private CommonMangerExtService commonMangerExtService;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private UcApiService ucApiService;

    @Autowired
    private CommonService commonService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private ProductNodeFlowDao productNodeFlowDao;
    @Autowired
    private ProductNodeOperatingDao productNodeOperatingDao;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 通过销售主单编号查询生产单json
     * @return
     */
    public OrderJson findOrderJsonByOrderNo(String orderNo){
        DggValidateUtil.notNull(orderNo, CommonExcption.class,"销售订单编号为空");
        return orderJsonDao.selectByOrderNo(orderNo);
    }

    /**
     * 修改json数据
     * @param order
     * @param params
     * @param type 1 新增  2 修改
     */
    @Transactional
    public void updateOrderJson(OrderJson order, Map params,Integer type) throws IOException {
        Object contractNo = params.get("contractNo");
        Object customerJson = params.get("customerJson");
        Object contactJson = params.get("concactJsonArr");
        Object orderBusinessJson = params.get("businessJsonArr");
        Object subjectJson = params.get("subjectJsonArr");
        Object loansAmount = params.get("loansAmount");
        Object loansNum = params.get("loansNum");
        Object loansInterest = params.get("loansInterest");
        Object loansRateType = params.get("loansRateType");
        Object earnestMoney = params.get("earnestMoney");
        Object mortgageAddress = params.get("mortgageAddress");
        DggValidateUtil.notNull(contractNo,CommonExcption.class,"合同编号为空！");
        DggValidateUtil.notNull(customerJson,CommonExcption.class,"客户数据为空！");
        DggValidateUtil.notNull(contactJson,CommonExcption.class,"借贷人数据为空！");
        DggValidateUtil.notNull(orderBusinessJson,CommonExcption.class,"办理业务数据为空！");
        DggValidateUtil.notNull(loansAmount,CommonExcption.class,"贷款金额为空！");
        DggValidateUtil.notNull(loansNum,CommonExcption.class,"贷款年限为空！");
        DggValidateUtil.notNull(loansInterest,CommonExcption.class,"贷款利息为空！");
        DggValidateUtil.notNull(loansRateType,CommonExcption.class,"利息方式为空！");
        DggValidateUtil.notNull(earnestMoney,CommonExcption.class,"定金为空！");

        //客户信息验证
        OrderCustomer orderCustomer = JsonUtil.json2Obj(customerJson.toString(), OrderCustomer.class);
        DggValidateUtil.notNull(orderCustomer,CommonExcption.class,"客户为空！");
        DggValidateUtil.notNull(orderCustomer.getCustomerId(),CommonExcption.class,"客户id为空！");
        DggValidateUtil.notNull(orderCustomer.getCustomerNo(),CommonExcption.class,"客户编号为空！");
        DggValidateUtil.notNull(orderCustomer.getCustomerName(),CommonExcption.class,"客户名称为空！");
        DggValidateUtil.notNull(orderCustomer.getIdCard(),CommonExcption.class,"身份证号为空！");
        DggValidateUtil.notNull(orderCustomer.getSex(),CommonExcption.class,"客户性别为空！");
        DggValidateUtil.notNull(orderCustomer.getAge(),CommonExcption.class,"客户年龄为空！");
        DggValidateUtil.notNull(orderCustomer.getBirthday(),CommonExcption.class,"客户生日为空！");
        DggValidateUtil.notNull(orderCustomer.getRegisteredResidence(),CommonExcption.class,"客户户口所在地为空！");
        DggValidateUtil.notNull(orderCustomer.getEduBackground(),CommonExcption.class,"客户学历为空！");
        DggValidateUtil.notNull(orderCustomer.getMaritalStatus(),CommonExcption.class,"客户婚姻状况为空！");
        DggValidateUtil.notNull(orderCustomer.getChildrenNum(),CommonExcption.class,"客户子女个数为空！");
        DggValidateUtil.notNull(orderCustomer.getAddress(),CommonExcption.class,"客户地址为空！");

        //借贷人验证
        List<OrderContact> orderContactList = JsonUtil.json2List(contactJson.toString(), OrderContact.class);
        if(orderContactList==null||orderContactList.size()<=0){
            DggValidateUtil.notNull(null,CommonExcption.class,"借贷人为空！");
        }
        if(orderContactList.size()>5){
            DggValidateUtil.notNull(null,CommonExcption.class,"借贷人最多5个！");
        }
        for(OrderContact orderContact : orderContactList){
            DggValidateUtil.notNull(orderContact.getLenderStatus(),CommonExcption.class,"借贷人身份为空！");
            DggValidateUtil.notNull(orderContact.getIsSelf(),CommonExcption.class,"借贷人是否本人为空！");
            DggValidateUtil.notNull(orderContact.getName(),CommonExcption.class,"借贷人姓名为空！");
            DggValidateUtil.notNull(orderContact.getCardId(),CommonExcption.class,"借贷人身份证号为空！");
            DggValidateUtil.notNull(orderContact.getNo(),CommonExcption.class,"借贷人联系电话为空！");
            DggValidateUtil.notNull(orderContact.getContactChildrenNum(),CommonExcption.class,"借贷人联系电话为空！");
            DggValidateUtil.notNull(orderContact.getContactChildrenNum(),CommonExcption.class,"借贷人子女情况为空！");
            DggValidateUtil.notNull(orderContact.getNoKnow(),CommonExcption.class,"借贷人家属是否知晓为空！");
            DggValidateUtil.notNull(orderContact.getRelationshipOfCus(),CommonExcption.class,"借贷人与主借贷人关系为空！");
            orderContact.setNo(desUtil.encrypt(orderContact.getNo()));
        }
        String contactJsonStr = JsonUtil.obj2Json(orderContactList);

        //办理业务验证
        List<ProductOrder> productOrders = JsonUtil.json2List(orderBusinessJson.toString(), ProductOrder.class);
        if(productOrders==null||productOrders.size()<=0) {
            DggValidateUtil.notNull(null,CommonExcption.class,"办理业务为空！");
        }
        for(ProductOrder productOrder : productOrders){
            DggValidateUtil.strNotEmpty(productOrder.getBusinessTypeCode(),CommonExcption.class,"办理业务类型为空！");
            DggValidateUtil.strNotEmpty(productOrder.getBusinessProductCode(),CommonExcption.class,"办理业务产品为空！");
            DggValidateUtil.notNull(productOrder.getServiceCharge(),CommonExcption.class,"办理业务手续费为空！");
            DggValidateUtil.notNull(productOrder.getRateType(),CommonExcption.class,"办理业务利率方式为空！");
            DggValidateUtil.notNull(productOrder.getLoanAmount(),CommonExcption.class,"办理业务贷款额度为空！");
            DggValidateUtil.strNotEmpty(productOrder.getContractNo(),CommonExcption.class,"办理业务合同编号为空！");
            DggValidateUtil.notNull(productOrder.getChannelId(),CommonExcption.class,"办理业务渠道为空！");
            DggValidateUtil.notNull(productOrder.getProductOrgId(),CommonExcption.class,"办理业务事业部为空！");
        }
        //解析成本费
        if(!StringUtils.isEmpty(subjectJson)){
            List<OrderSubject> orderSubjects = JsonUtil.json2List(subjectJson.toString(), OrderSubject.class);
            if(orderSubjects!=null&&orderSubjects.size()>10){
                DggValidateUtil.notNull(null,CommonExcption.class,"成本费最多10条！");
            }
        }

        if(order==null){
            order = new OrderJson();
        }
        order.setFlag(0);
        order.setContractNo(contractNo.toString());
        order.setCustomerJson(customerJson.toString());
        order.setContactJson(contactJsonStr);
        order.setOrderBusinessJson(orderBusinessJson.toString());
        order.setSubjectJson(subjectJson==null?"":subjectJson.toString());
        order.setLoansAmount(new BigDecimal(loansAmount.toString()));
        order.setLoansNum(Double.parseDouble(loansNum.toString()));
        order.setLoansInterest(Double.parseDouble(loansInterest.toString()));
        order.setLoansRateType(loansRateType.toString());
        order.setEarnestMoney(new BigDecimal(earnestMoney.toString()));
        order.setMortgageAddress(mortgageAddress==null?"":mortgageAddress.toString());
        if(type==1){
            order.setId(DggKeyWorker.nextId());
            orderJsonDao.insertSelective(order);
        }else{
            orderJsonDao.updateByPrimaryKey(order);
        }

        Map notiMap = new HashMap<String,Object>();
        notiMap.put("orderId", order.getOrderId());
        notiMap.put("status", "ORF_DDZT_ORDER_OK");
        HttpUtility.postRest(order.getNotifyUrl(),notiMap);//通知


    }

    /**
     * 生成生产订单
     * @param orderJson
     */

    @Transactional
    public void createProductOrder(OrderJson orderJson,String order) {
        //解析订单
        JSONObject orderObj = JSONObject.parseObject(order);
        Long curentUserId = 1L;//当前登录用户id,超级管理员
        UserEntity userEntity;//当前登录人
        Map curentDept;//当前登录人部门
        if (!StringUtils.isEmpty(orderObj.get("createrId"))){
            //传过来的创建者
            userEntity = userService.findUserById(Long.valueOf(orderObj.get("createrId").toString()));
            curentDept = this.commonMangerExtService.findOrg(userEntity.getOrgId());
        }else {
            //超级管理员
            userEntity = userService.findUserById(curentUserId);
            curentDept = this.commonMangerExtService.findOrg(userEntity.getOrgId());
        }

        DggValidateUtil.notNull(userEntity,CommonExcption.class,"登陆人为空，请重新登陆！");

        //解析并保存客户信息
        OrderCustomer orderCustomer = JsonUtil.json2Obj(orderJson.getCustomerJson(), OrderCustomer.class);
        String customerPhone = orderCustomer.getCustomerPhone();
        orderCustomer.setId(DggKeyWorker.nextId());
        orderCustomer.setOrderNo(orderJson.getOrderNo());
        orderCustomer.setCustomerPhone(customerPhone);
        this.saveOpt(orderCustomer,userEntity);
        orderCustomer.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
        orderCustomer.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
        orderCustomerDao.insert(orderCustomer);

        //解析并保存借贷人
        List<OrderContact> orderContactList = JsonUtil.json2List(orderJson.getContactJson(), OrderContact.class);
        for(OrderContact orderContact:orderContactList){
            orderContact.setId(DggKeyWorker.nextId());
            String contactPhone = orderContact.getNo();
            this.saveOpt(orderContact,userEntity);
            orderContact.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            orderContact.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            orderContact.setNo(contactPhone);
            orderContact.setOrderNo(orderJson.getOrderNo());
            orderContactDao.insert(orderContact);
        }


        List<JSONObject> productOrderJson=JsonUtil.json2List(orderJson.getOrderBusinessJson(), JSONObject.class);
        List<ProductOrder> productOrders = new ArrayList<>();
        for (JSONObject jsonObject : productOrderJson) {
            jsonObject.put("goodsId", jsonObject.getString("productGoodsId"));
            jsonObject.put("goodsName", jsonObject.getString("productAttr"));
            ProductOrder productOrder = JsonUtil.json2Obj(jsonObject.toJSONString(), ProductOrder.class);
            productOrders.add(productOrder);
        }

        for(ProductOrder productOrder:productOrders){
            productOrder.setId(DggKeyWorker.nextId());
            productOrder.setContractNo(orderJson.getContractNo());
            this.saveOpt(productOrder,userEntity);
            productOrder.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            productOrder.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            //插入流程id
            Map maps = new HashMap<>();
            Long serialId = commonService.getSerialId(productOrder.getProductId());
            maps.put("productId", serialId);
            maps.put("businessTypeCode", productOrder.getBusinessTypeCode());//一级业态Code
            maps.put("smallBusinessTypeCode", productOrder.getBusinessProductCode());// 二级业态Code
            ProductNodeFlow nodeFlow =  getNodeFlow(maps);

            DggValidateUtil.notNull(nodeFlow, CommonExcption.class, "未查询到["+productOrder.getBusinessProductName()+"/"+productOrder.getProductName()+"]流程节点的配置信息");
            productOrder.setNodeFlowId(nodeFlow.getId());
            productOrder.setVersion(nodeFlow.getVersion());
            productOrder.setOrderLoansInterest(orderJson.getLoansInterest());
            productOrder.setMortgageAddress(orderJson.getMortgageAddress());
            //接入企大宝任务模板保存json字段
            List<ProductNode> nodeList = getProductNode(nodeFlow);
            String nodeStr = JSONObject.toJSONString(nodeList);
            productOrder.setNodeJson(nodeStr);//设置节点数据
            //补全信息
            this.completionProductOrder(productOrder,orderObj,orderCustomer);
            productOrderDao.insertSelective(productOrder);
            //插入操作记录
            SystemRecord record = new SystemRecord();
            record.setId(DggKeyWorker.nextId());
            record.setSource("3");//接口
            record.setWorkTableName("rzsc_product_order");
            record.setWorkId(productOrder.getId());
            record.setWorkNo(productOrder.getScProductOrderNo());
            record.setBeOperaterId(userEntity.getId());
            record.setOperateType("1");
            record.setRemarks("新增生产订单");
            record.setOperaterId(userEntity.getOrgId());//操作人员id
            record.setOperaterName(userEntity.getRealName());//操作人员名称
            record.setOperateTime(new Date());//操作时间
            systemRecordService.apiSave(record, userEntity);

            //生产订单超期
            Date now = new Date();
            ProductTimeStatus timestatus = new ProductTimeStatus();
            timestatus.setId(productOrder.getId());
            timestatus.setScProductOrderNo(productOrder.getScProductOrderNo());
            timestatus.setNodeFlowId(productOrder.getNodeFlowId());
            if(nodeFlow.getIsnaturalorworkday()==1) {//工作日
                Date nowDate = new Date();
                String orderEndTime = cmsService.findAfterDate(DateUtil.dateToString(nowDate,"yyyy-MM-dd HH:mm:ss"),nodeFlow.getManagementCycle())+" "+DateUtil.dateToString(nowDate,"HH:mm:ss");
                timestatus.setOrderEndTime(DateUtil.stringToDate(orderEndTime,"yyyy-MM-dd HH:mm:ss"));
            }else {
                try {
                    timestatus.setOrderEndTime(DateUtils.dateAddDayJs(new Date(), nodeFlow.getManagementCycle()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);
            timestatus.setDistributionStartTime(now);//计时开始时间
            timestatus.setDistributionTimeOutStatus(ScProductConstant.NORMAL);
            try {
                timestatus.setDistributionEndTime(DateUtils.dateAddDayJs(now, 1));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(productOrder.getFlowUserId() != null){
                timestatus.setReceiveStartTime(now);
                timestatus.setReceiveProcessTime(1);
                try {
                    timestatus.setReceiveEndTime(commonService.getWorkDateFrom(now,1));
                    timestatus.setReceiveTimeStatus(ScProductConstant.NORMAL);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            timestatus.setFlag(1);//必须要加入
            timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);//写入节点超期状态,默认不超期
            timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);
            this.saveOpt(timestatus,userEntity);
            timestatus.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            timestatus.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            timestatus.setOrderStartTime(now);
            timestatus.setOrderProcessTime(nodeFlow.getManagementCycle());
            timestatus.setOrderProcessTimeType(nodeFlow.getIsnaturalorworkday());
            productTimeStatusDao.insertSelective(timestatus);

            try {
                if(null != productOrder && ScProductConstant.RZSCORDER_STATUS01.equals(productOrder.getStatus())&& productOrder.getFlowUserId() != null){
                    //推送消息到企业微信
                    String[] msgs = new String[]{productOrder.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                    cmsService.sendMessage(productOrder.getFlowUserId(), 1L, msgs, MsgConstant.RZSC_SC_ALLOCATE, 1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        //解析成本费
        if(!StringUtils.isEmpty(orderJson.getSubjectJson())){
            List<OrderSubject> orderSubjects = JsonUtil.json2List(orderJson.getSubjectJson(), OrderSubject.class);
            for(OrderSubject orderSubject:orderSubjects){
                orderSubject.setId(DggKeyWorker.nextId());
                orderSubject.setOrderNo(orderJson.getOrderNo());
                this.saveOpt(orderSubject,userEntity);
                orderSubject.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
                orderSubject.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
                orderSubjectDao.insertSelective(orderSubject);
            }
        }

        //修改orderJson 的状态为已经生成生产订单
        OrderJson newOrderJson =  new OrderJson();
        newOrderJson.setId(orderJson.getId());
        newOrderJson.setFlag(1);
        this.updateOpt(newOrderJson,userEntity);
        newOrderJson.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());

        orderJsonDao.updateByPrimaryKeySelective(newOrderJson);

        //更新客户信息到uc
        try {
            Map params = new HashMap();
            params.put("id",orderCustomer.getCustomerId());
            params.put("name",orderCustomer.getCustomerName());
            params.put("sex",orderCustomer.getSex());
            params.put("birthday",orderCustomer.getBirthday());
            params.put("age",orderCustomer.getAge());
            params.put("idCard",orderCustomer.getIdCard());
            params.put("address",orderCustomer.getAddress());
            params.put("houseRegister",orderCustomer.getRegisteredResidence());
            params.put("education",orderCustomer.getEduBackground());
            params.put("maritalStatus",orderCustomer.getMaritalStatus());
            params.put("childrens",orderCustomer.getChildrenNum());
            params.put("updaterId",userEntity.getId());
            ucApiService.updateCustomer(params);
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    /**
     * 补全生产单数据
     * @param productOrder
     * @param orderObj
     */

    private void completionProductOrder(ProductOrder productOrder,JSONObject orderObj,OrderCustomer orderCustomer){

        //获取生产子订单编号
        String number = cmsService.getBillNumber("sc");
        DggValidateUtil.notNull(number,CommonExcption.class,"单据号获取失败,请联系管理员！");
        productOrder.setId(DggKeyWorker.nextId());
        productOrder.setOriginCode(ScProductConstant.RZSC_ORIGINCODE_UNDER);
        productOrder.setScProductOrderNo(number);
        productOrder.setOrderId(orderObj.get("orderId") == null ? null : orderObj.getLong("orderId"));
        productOrder.setOrderNo(orderObj.get("orderNo").toString());
        productOrder.setBusinessId(orderObj.get("businessId") == null ? null : orderObj.getLong("businessId"));
        productOrder.setBusinessNo(orderObj.get("businessNo") == null ? null : orderObj.getString("businessNo"));
        productOrder.setCustomerId(orderObj.get("customerId") == null ? null : orderObj.getLong("customerId"));
        productOrder.setCustomerNo(orderObj.get("customerNo").toString());
        String customerPhone = "";
        String contactPhone = "";
        if(!StringUtils.isEmpty(orderObj.get("customerPhone"))) {
            customerPhone = orderObj.get("customerPhone").toString();
        }
        if(!StringUtils.isEmpty(orderObj.get("contactPhone"))) {
            contactPhone = orderObj.get("contactPhone").toString();
        }
        productOrder.setCustomerNo(orderObj.get("customerNo").toString());
        productOrder.setCustomerPhone(customerPhone);
        productOrder.setCustomerName(orderCustomer.getCustomerName());
        productOrder.setContactPhone(contactPhone);
        productOrder.setOrderTime(orderObj.get("signDate") == null ? null : orderObj.getDate("signDate"));
        productOrder.setMoney(orderObj.get("money") == null ? null : new BigDecimal(orderObj.getString("money")));
        productOrder.setPayMethod(orderObj.get("payMethod") == null ? null : orderObj.getString("payMethod"));
        productOrder.setSignUserId(orderObj.get("signUserId") == null ? null : orderObj.getLong("signUserId"));
        productOrder.setSignUserName(orderObj.get("signUserName") == null ? null : orderObj.getString("signUserName"));
        Long signOrgId = orderObj.get("signOrgId") == null ? null : orderObj.getLong("signOrgId");
        if (null != signOrgId) {
            Map deptMap = this.commonMangerExtService.findOrg(signOrgId);
            if (null != deptMap) {
                productOrder.setSignUserOrgId(Long.parseLong(deptMap.get("id").toString()));
                productOrder.setSignUserOrgName(deptMap.get("name").toString());
            }
        }
        productOrder.setSignOrgId(orderObj.get("sourceDeptId") == null ? null : orderObj.getLong("sourceDeptId"));
        productOrder.setSignOrgName(orderObj.get("sourceDeptName") == null ? null : orderObj.getString("sourceDeptName"));
        productOrder.setSignTime(orderObj.get("signDate") == null ? null : orderObj.getDate("signDate"));
        if(productOrder.getFlowUserId() != null){
            Map userMap = cmsService.findUser(productOrder.getFlowUserId());
            if (null != userMap) {
                String realName = userMap.get("realName")==null?"":userMap.get("realName").toString();
                String loginName = userMap.get("loginName")==null?"":userMap.get("loginName").toString();
                Long orgId = userMap.get("orgId")==null?null:Long.parseLong(userMap.get("orgId").toString());
                String orgName = userMap.get("orgName")==null?"":userMap.get("orgName").toString();
                productOrder.setFlowUserName(realName+loginName);
                productOrder.setFlowUserOrgId(orgId);
                productOrder.setFlowUserOrgName(orgName);

            }
            productOrder.setAllotDate(new Date());
            productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS01);//下单待接收
        }else{
            productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS14);//待分配
        }

    }


    /**
     * 补全生产单数据
     * @param productOrder
     */

    private void completionProductOrderQds(ProductOrder productOrder,GsScOrderVo gsScOrderVo,QdsScOrderVo qdsScOrderVo,OrderBusinessVo orderBusinessVo){

        //获取生产子订单编号
        OrderVo orderVo = qdsScOrderVo.getOrderVo();
        productOrder.setOriginCode(ScProductConstant.RZSC_ORIGINCODE_UNDER);
        productOrder.setOrderSource(SystemCommonConstant.QDS_SC);
        productOrder.setId(gsScOrderVo.getQdsScId());
        productOrder.setScProductOrderNo(gsScOrderVo.getQdsScNo());
        productOrder.setContractNo(orderVo.getContractNo());
        productOrder.setOrderId(orderVo.getOrderId());
        productOrder.setOrderNo(orderVo.getOrderNo());
        productOrder.setOrderBusId(orderBusinessVo.getOrderBusinessId());
        productOrder.setOrderBusNo(orderBusinessVo.getOrderBusinessNo());
        productOrder.setBusinessId(orderVo.getBusinessId());
        productOrder.setBusinessNo(orderVo.getBusinessNo());
        productOrder.setCustomerId(orderVo.getCustomerId());
        productOrder.setCustomerNo(orderVo.getCustomerNo());
        productOrder.setCustomerPhone(orderVo.getContactPhone());
        productOrder.setCustomerName(orderVo.getCustomerName());
        productOrder.setContactPhone(orderVo.getContactPhone());
        productOrder.setOrderTime(orderVo.getPlaceOrderTime());
        productOrder.setFlowUserId(qdsScOrderVo.getFlowerId());
        productOrder.setRemark(qdsScOrderVo.getAlotNote());
        productOrder.setMoney(orderVo.getAmount());
        productOrder.setPayMethod(orderVo.getPayMethod());
        productOrder.setSignUserId(orderVo.getBusinessUserId());
        productOrder.setSignUserName(orderVo.getBusinessUserName());
        productOrder.setProductId(orderBusinessVo.getProductId());
        productOrder.setProductName(orderBusinessVo.getProductName());
        productOrder.setProductOrgId(orderVo.getProductOrgId());
        productOrder.setProductOrgName(orderVo.getProductOrgName());
        productOrder.setBusinessProductCode(orderBusinessVo.getSmallBusiness());
        productOrder.setBusinessProductName(orderBusinessVo.getSmallBusinessName());
        productOrder.setGoodsId(orderBusinessVo.getProductGoodsId());
        productOrder.setGoodsName(orderBusinessVo.getProductSpec());
        productOrder.setLastRemark(orderVo.getRemark());
        productOrder.setLastRemarkTime(new Date());
        productOrder.setLatestEndNodeTime(new Date());
        productOrder.setBusinessTypeCode(orderVo.getBusinessTypeNo());
        productOrder.setBusinessTypeName(orderVo.getBusinessTypeName());
        Long signOrgId = orderVo.getSignOrgId();
        if (null != signOrgId) {
            Map deptMap = this.commonMangerExtService.findOrg(signOrgId);
            if (null != deptMap) {
                productOrder.setSignUserOrgId(Long.parseLong(deptMap.get("id").toString()));
                productOrder.setSignUserOrgName(deptMap.get("name").toString());
            }
        }
        productOrder.setSignOrgId(signOrgId);
        productOrder.setSignOrgName(orderVo.getSignOrgName());
        productOrder.setSignTime(orderVo.getPlaceOrderTime());
        if(productOrder.getFlowUserId() != null){
            Map userMap = cmsService.findUser(productOrder.getFlowUserId());
            if (null != userMap) {
                String realName = userMap.get("realName")==null?"":userMap.get("realName").toString();
                String loginName = userMap.get("loginName")==null?"":userMap.get("loginName").toString();
                Long orgId = userMap.get("orgId")==null?null:Long.parseLong(userMap.get("orgId").toString());
                String orgName = userMap.get("orgName")==null?"":userMap.get("orgName").toString();
                productOrder.setFlowUserName(realName+loginName);
                productOrder.setFlowUserOrgId(orgId);
                productOrder.setFlowUserOrgName(orgName);

            }
            productOrder.setAllotDate(new Date());
            productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS01);//下单待接收
        }else{
            productOrder.setStatus(ScProductConstant.RZSCORDER_STATUS14);//待分配
        }

    }

    /**
     * <p>@Description 接口专用: 根据销售订单ID查询所有生产订单信息</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/9/19 0019 14:16 创建时间</p>
     * <p>@return</p>
     */
    public String queryProductOrderByOrderId(Long orderId) {
        ValidateUtils.strNotEmpty(orderId,CommonExcption.class,"销售订单ID不能为空!");
        List<Map> mapList = productOrderDao.queryProductOrderByOrderId(new HashMap() {{
            put("orderId", orderId);
        }});
        String data = JsonUtil.obj2Json(mapList);

        return data;
    }


    /**
     * @Title:
     * @Description: 会员中心通过销售订单ID获取生产订单最新节点信息
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2019/2/23
     **/
    public Map getScOrderLatestNodeByOrderId(Map<String, Object> params) {
        Map map = new HashMap();
        ProductOrder gsscProductOrder = productOrderDao.queryLatestScOrder(params);
        map.put("productName", gsscProductOrder == null ? "" : gsscProductOrder.getProductName() == null ? "" : gsscProductOrder.getProductName());
        map.put("latestNode", gsscProductOrder == null ? "" : gsscProductOrder.getLatestEndNodeName() == null ? "" : gsscProductOrder.getLatestEndNodeName());
        return map;
    }


    /**
     * @Title:
     * @Description: 会员中心通过销售订单ID获取生产订单业务办理进度
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2019/2/23
     **/
    public List<List<Map<String, Object>>> queryBusProgress(Long orderId) {
        List<ProductOrder> scOrderList = productOrderDao.queryAllScorder(orderId);
        List<List<Map<String, Object>>> allBusinessList = new ArrayList<>();

        for (ProductOrder productOrder: scOrderList) {
            List<Map<String, Object>> businessList = new ArrayList<>();
            Map map = new HashMap();
            List<LinkedHashMap> newprogressList = new ArrayList<>();
            Long scOrderId = productOrder.getId();
            Map<String, Object> params = new HashMap<>();
            params.put("scorderId", scOrderId);
			/*单个查询生产订单基本信息*/
            Long flowUserId = productOrder.getFlowUserId();
            if (flowUserId != null) {
                Map userMap = commonMangerExtService.searchUserById(flowUserId);
               /*查询订单历史更新节点记录信息*/
                List<LinkedHashMap> progressList = productOrderDao.queryBusinessProgress(params);
					/*为每个节点记录注入流程人员信息，本应该取记录创建者去循环获取用户信息，因考虑查询效率问题改为获取当前订单的流程人员放置到每个节点上*/
                for (LinkedHashMap nodeMap : progressList) {
                    nodeMap.put("nodeOrgName", String.valueOf(userMap.get("orgName")));
                    nodeMap.put("nodeUserName", String.valueOf(userMap.get("realName")));
                    nodeMap.put("nodePhone", String.valueOf(userMap.get("phone")));
                    newprogressList.add(nodeMap);
                }
					/*给list注入当前节点信息*/
                /*if (!StringUtils.isEmpty(productOrder.getLatestEndNodeName())) {
                    LinkedHashMap nowNodeMap = new LinkedHashMap();
                    nowNodeMap.put("nodeName", productOrder.getLatestEndNodeName());
                    nowNodeMap.put("progress", "OVERDUE_STATE0");
                    nowNodeMap.put("nodeOverdueTime", null);
                    nowNodeMap.put("createTime", null);
                    nowNodeMap.put("nodeOrgName", String.valueOf(userMap.get("orgName")));
                    nowNodeMap.put("nodeUserName", String.valueOf(userMap.get("realName")));
                    nowNodeMap.put("nodePhone", String.valueOf(userMap.get("phone")));
                    newprogressList.add(nowNodeMap);
                }*/
            }
            map.put("progressList", newprogressList);
            map.put("productName",productOrder.getProductName());

            businessList.add(map);
            allBusinessList.add(businessList);
        }

        return allBusinessList;
    }

    /**
     *根据销售订单ID查询所有完结生产订单放款信息
     * @param orderId
     * @return
     */
    public String queryLoanMoneyByOrderId(Long orderId) {
        ValidateUtils.strNotEmpty(orderId,CommonExcption.class,"销售订单ID不能为空!");
        List<Map> mapList = productOrderDao.queryLoanMoneyByOrderId(new HashMap() {{
            put("orderId", orderId);
        }});
        String data = JsonUtil.obj2Json(mapList);

        return data;
    }
    /**
     * 刷新号码加密问题
     */
    public int queryJsonCount() {
        return orderJsonDao.queryJsonCount();
    }
    /**
     * 刷新号码加密问题
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateJson() {
        //查询5000条数据出来
        List<OrderJson> orderJsons = orderJsonDao.queryJsons();
        if(orderJsons != null && orderJsons.size()>0){
            for(OrderJson orderJson:orderJsons){
                Map orderMap = JsonUtil.json2Obj(orderJson.getOrderJson(),Map.class);
                String customerPhone = orderMap.get("customerPhone")==null?"":orderMap.get("customerPhone").toString();
                String contactPhone = orderMap.get("contactPhone")==null?"":orderMap.get("contactPhone").toString();
                if(!StringUtils.isEmpty(customerPhone) && customerPhone != "null" && customerPhone.length()<15){
                    orderMap.put("customerPhone",desUtil.encrypt(customerPhone));//加密电话号码
                }
                if(!StringUtils.isEmpty(contactPhone) && contactPhone != "null" && contactPhone.length()<15){
                    orderMap.put("contactPhone",desUtil.encrypt(contactPhone));//加密电话号码
                }

                //借贷人
                String contactJson = orderJson.getContactJson();
                String contactJsonMap = "";
                if (!StringUtils.isEmpty(contactJson)){
                    List<OrderContact> orderContactList = JsonUtil.json2List(contactJson.toString(), OrderContact.class);
                    if(orderContactList != null && orderContactList.size()>0){
                        for (OrderContact orderContact : orderContactList){
                            if(!StringUtils.isEmpty(orderContact.getNo())&&orderContact.getNo() != "null" && orderContact.getNo().length()<15){
                                String no = orderContact.getNo();
                                orderContact.setNo(desUtil.encrypt(no));
                            }
                        }
                        contactJsonMap = JsonUtil.obj2Json(orderContactList);
                    }
                }
                orderJson.setOrderJson(JsonUtil.obj2Json(orderMap));
                orderJson.setContactJson(contactJsonMap);
                orderJsonDao.updateJson(orderJson);

            }
        }
    }
    /**
     * 接收企大顺分配的订单
     * sdx
     */
    @Transactional(rollbackFor = Exception.class)
    public void allotScOrder(@Validated QdsScOrderVo qdsScOrderVo) {
        //保存orderJson,首先查询数据库是否存在相关销售单数据
        OrderVo orderVo = qdsScOrderVo.getOrderVo();

        LoginUser userEntity = qdsScOrderVo.getLoginUser();
        Long curentUserId = 1L;//当前登录用户id,超级管理员
        UserEntity userentity;//当前登录人
        Map curentDept;//当前登录人部门
        if (!StringUtils.isEmpty(userEntity.getUserId())){
            //传过来的创建者
            userentity = userService.findUserById(Long.valueOf(userEntity.getUserId()));
            curentDept = this.commonMangerExtService.findOrg(userentity.getOrgId());
        }else {
            //超级管理员
            userentity = userService.findUserById(curentUserId);
            curentDept = this.commonMangerExtService.findOrg(userentity.getOrgId());
        }
        //todo 通过订单ID查询orderJson
        OrderJson orderJson = orderJsonDao.selectByOrderId(orderVo.getOrderId());
        //todo 如果查询未orderJson，直接新增
        if(null == orderJson){
            orderJson = new OrderJson();
            orderJson.setId(DggKeyWorker.nextId());
            orderJson.setOrderId(orderVo.getOrderId());
            orderJson.setOrderNo(orderVo.getOrderNo());
            orderJson.setOrderSource(SystemCommonConstant.QDS_SC);
            orderJson.setFlag(1);
            this.saveOpt(orderJson,userentity);
            this.updateOpt(orderJson,userentity);
            orderJson.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            //todo 组装orderJson数据
            String orderObject= getOrderJson(qdsScOrderVo,userentity,curentDept);
            orderJson.setOrderJson(orderObject);
            //todo 组装orderBusinessJson数据
            String orderBusinessObject = getOrderBusinessJson(qdsScOrderVo,null);
            orderJson.setOrderBusinessJson(orderBusinessObject);
            //todo 保存生产订单
            createProductOrderQds(qdsScOrderVo,userentity,curentDept);
            orderJsonDao.insertSelective(orderJson);
        }else{
            //todo 如果查询到orderJson做编辑操作
            this.updateOpt(orderJson,userentity);
            //todo 组装orderBusinessJson数据
            List<JSONObject> productOrderJson=JsonUtil.json2List(orderJson.getOrderBusinessJson(), JSONObject.class);
            String orderBusinessObject = getOrderBusinessJson(qdsScOrderVo,productOrderJson);
            orderJson.setOrderBusinessJson(orderBusinessObject);
            List<GsScOrderVo> gsScOrderVoList = qdsScOrderVo.getGsScOrderVos();
            List<Long> scProductOrderIdList = new ArrayList<>();
            for(GsScOrderVo gsScOrderVo:gsScOrderVoList){
                scProductOrderIdList.add(gsScOrderVo.getQdsScId());
            }
            List<ProductOrder> productOrders = productOrderDao.selectByPrimaryKeys(scProductOrderIdList);
            if(CollectionUtils.isEmpty(productOrders)){
                createProductOrderQds(qdsScOrderVo,userentity,curentDept);
            }else{
                return;
            }
            orderJsonDao.updateByPrimaryKeySelective(orderJson);
        }

    }

    /**
     * 将企大宝获取到的订单数据拼接为orderJson
     * @param qdsScOrderVo
     * @param userentity
     * @param curentDept
     * @return
     */
    public String getOrderJson(QdsScOrderVo qdsScOrderVo,UserEntity userentity,Map curentDept){
        OrderVo orderVo = qdsScOrderVo.getOrderVo();
        JSONObject order = new JSONObject();
        order.put("businessAreaCode","");
        order.put("businessId",orderVo.getBusinessId());
        order.put("businessNo",orderVo.getBusinessNo());
        order.put("businessTypeId",orderVo.getBusinessTypeNo());
        order.put("businessTypeName",orderVo.getBusinessTypeName());
        order.put("contactPhone",orderVo.getContactPhone());
        order.put("contractNo",orderVo.getContractNo());
        order.put("createTime",System.currentTimeMillis());
        order.put("createrId",userentity.getId());
        order.put("createrName",userentity.getRealName()+"/"+userentity.getLoginName());
        order.put("customerId",orderVo.getCustomerId());
        order.put("customerName",orderVo.getCustomerName());
        order.put("customerNo",orderVo.getCustomerNo());
        order.put("customerPhone","");
        order.put("isBlankContract","");
        order.put("isBusinessSingle","");
        order.put("money",orderVo.getAmount());
        order.put("orderId",orderVo.getOrderId());
        order.put("orderNo",orderVo.getOrderNo());
        order.put("payMethod",orderVo.getPayMethod());
        order.put("proOrgId",orderVo.getProductOrgId());
        order.put("proOrgName",orderVo.getProductOrgName());
        order.put("remark",orderVo.getRemark());
        order.put("scOrderNo",qdsScOrderVo.getGsScOrderVos());
        order.put("signDate",System.currentTimeMillis());
        order.put("signOrgId",null == curentDept ? null : curentDept.get("id").toString());
        order.put("signUserId",userentity.getId());
        order.put("signUserName",userentity.getRealName()+"/"+userentity.getLoginName());
        order.put("signUserOrgName",orderVo.getSignOrgName());
        order.put("sourceDeptId",orderVo.getPlaceOrderOrgId());
        order.put("sourceDeptName",orderVo.getPlaceOrderOrgName());
        return order.toJSONString();
    }

    /**
     * 将企大宝获取到的订单数据拼接为orderBusinessJson
     * @param qdsScOrderVo
     * @param jsonObjects
     * @return
     */
    public String getOrderBusinessJson(QdsScOrderVo qdsScOrderVo,List<JSONObject> jsonObjects){
        OrderVo orderVo = qdsScOrderVo.getOrderVo();
        List<GsScOrderVo> gsScOrderVos = qdsScOrderVo.getGsScOrderVos();
        List<JSONObject> retJsonObjects = new ArrayList<>();
        //orderJson已存在，编辑操作，添加原有的产品
        if (!CollectionUtils.isEmpty(jsonObjects)){
            List<OrderBusinessVo> orderBusinessVos = new ArrayList<>();
            for (GsScOrderVo gsScOrderVo:gsScOrderVos){
                orderBusinessVos.addAll(gsScOrderVo.getOrderBusinessVos());
            }
            retJsonObjects.addAll(jsonObjects);
            //定义变量 销售子单是否包含在原有部分
            boolean isOrderBusiness = false;
            for (OrderBusinessVo orderBusinessVo:orderBusinessVos){
                for(JSONObject jsonObject:jsonObjects){
                    if(orderBusinessVo.getOrderBusinessId().equals(jsonObject.getLong("orderBusId"))){
                        isOrderBusiness = true;
                        continue;
                    }
                }
            }
            //如果不包含，则直接追加
            if(!isOrderBusiness){
                for (GsScOrderVo gsScOrderVo:gsScOrderVos){
                    List<JSONObject> objects = comOrderBusinessJson(gsScOrderVo.getOrderBusinessVos(),gsScOrderVo,orderVo);
                    retJsonObjects.addAll(objects);
                }
            }else {
                //如果包含只追加不包含部分
                for (GsScOrderVo gsScOrderVo:gsScOrderVos){
                    for (OrderBusinessVo orderBusinessVo:orderBusinessVos){
                        for(JSONObject jsonObject:jsonObjects){
                            if(!orderBusinessVo.getOrderBusinessId().equals(jsonObject.getLong("orderBusId"))){
                                List<OrderBusinessVo> orderBusinessVosNew = new ArrayList<>();
                                orderBusinessVosNew.add(orderBusinessVo);
                                List<JSONObject> objects = comOrderBusinessJson(orderBusinessVosNew,gsScOrderVo,orderVo);
                                retJsonObjects.addAll(objects);
                            }
                        }
                    }
                }

            }
        // 直接追加orderBusinessJson
        }else{
            for (GsScOrderVo gsScOrderVo:gsScOrderVos){
                retJsonObjects = comOrderBusinessJson(gsScOrderVo.getOrderBusinessVos(),gsScOrderVo,orderVo);
            }

        }

        return JsonUtil.obj2Json(retJsonObjects);
    }

    /**
     * 拼装orderBusinessJson
     * @param orderBusinessVos
     * @param gsScOrderVo
     * @param orderVo
     * @return
     */
    private List<JSONObject> comOrderBusinessJson(List<OrderBusinessVo> orderBusinessVos,GsScOrderVo gsScOrderVo,OrderVo orderVo){
        List<JSONObject> jsonObjects = new ArrayList<>();
        JSONObject jsonObject = null;
        for(OrderBusinessVo orderBusinessVo:orderBusinessVos){
            jsonObject = new JSONObject();
            jsonObject.put("businessProductId",orderBusinessVo.getSmallBusiness());
            jsonObject.put("businessProductName","");
            jsonObject.put("businessTypeId",orderBusinessVo.getBtIdentifying());
            jsonObject.put("businessTypeName",orderBusinessVo.getBtName());
            jsonObject.put("contractNo",orderVo.getContractNo());
            jsonObject.put("money",orderBusinessVo.getProductAmount());
            jsonObject.put("orderBusId",orderBusinessVo.getOrderBusinessId());
            jsonObject.put("orderBusNo",orderBusinessVo.getOrderBusinessNo());
            jsonObject.put("orderId",orderBusinessVo.getOrderId());
            jsonObject.put("orderTime",System.currentTimeMillis());
            jsonObject.put("payMethod",orderVo.getPayMethod());
            jsonObject.put("productAttr",orderBusinessVo.getProductSpec());
            jsonObject.put("productGoodsId",orderBusinessVo.getProductGoodsId());
            jsonObject.put("productId",orderBusinessVo.getProductId());
            jsonObject.put("productName",orderBusinessVo.getProductName());
            jsonObject.put("productOrgId",orderVo.getProductOrgId());
            jsonObject.put("productOrgName",orderVo.getProductOrgName());
            jsonObject.put("remark",orderVo.getRemark());
            jsonObject.put("scOrderId",gsScOrderVo.getQdsScId());
            jsonObject.put("scProductOrderId",gsScOrderVo.getQdsScId());
            jsonObject.put("serviceArea","");
            jsonObjects.add(jsonObject);
        }
        return jsonObjects;

    }

    public void createProductOrderQds(QdsScOrderVo qdsScOrderVo,UserEntity userEntity,Map curentDept){
        List<GsScOrderVo> gsScOrderVos = qdsScOrderVo.getGsScOrderVos();

        ProductOrder productOrderNew = null;
        for(GsScOrderVo gsScOrderVo:gsScOrderVos){
            OrderBusinessVo orderBusinessVo = gsScOrderVo.getOrderBusinessVos().get(0);
            productOrderNew = new ProductOrder();
            this.saveOpt(productOrderNew,userEntity);
            this.updateOpt(productOrderNew,userEntity);
            productOrderNew.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            productOrderNew.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            //插入流程id
            Map maps = new HashMap<>();
            Long serialId = commonService.getSerialId(orderBusinessVo.getProductId());
            maps.put("productId", serialId);
            maps.put("businessTypeCode", orderBusinessVo.getBtIdentifying());//一级业态Code
            maps.put("smallBusinessTypeCode", orderBusinessVo.getSmallBusiness());// 二级业态Code
            ProductNodeFlow nodeFlow =  getNodeFlow(maps);

//            ProductNodeFlow node = productNodeFlowDao.queryFlowAndNodeVersionByBusinessAndProductId(maps);
            DggValidateUtil.notNull(nodeFlow, CommonExcption.class, "未查询到["+orderBusinessVo.getSmallBusinessName()+"/"+orderBusinessVo.getProductName()+"]流程节点的配置信息");
            productOrderNew.setNodeFlowId(nodeFlow.getId());
            productOrderNew.setVersion(nodeFlow.getVersion());
            productOrderNew.setGoodsId(orderBusinessVo.getProductGoodsId());
            productOrderNew.setGoodsName(orderBusinessVo.getProductSpec());
            //接入企大宝任务模板保存json字段
            List<ProductNode> nodeList = getProductNode(nodeFlow);
            String nodeStr = JSONObject.toJSONString(nodeList);
            logger.info("节点数据>>>>>>>>>>>>>"+nodeStr);
            productOrderNew.setNodeJson(nodeStr);//设置节点数据
            //补全信息
            this.completionProductOrderQds(productOrderNew,gsScOrderVo,qdsScOrderVo,orderBusinessVo);
            productOrderDao.insertSelective(productOrderNew);
            //插入操作记录
            SystemRecord record = new SystemRecord();
            record.setId(DggKeyWorker.nextId());
            record.setSource("3");//接口
            record.setWorkTableName("rzsc_product_order");
            record.setWorkId(productOrderNew.getId());
            record.setWorkNo(productOrderNew.getScProductOrderNo());
            record.setBeOperaterId(userEntity.getId());
            record.setOperateType("1");
            record.setRemarks("新增生产订单");
            record.setOperaterId(userEntity.getOrgId());//操作人员id
            record.setOperaterName(userEntity.getRealName());//操作人员名称
            record.setOperateTime(new Date());//操作时间
            systemRecordService.apiSave(record, userEntity);

            //生产订单超期
            Date now = new Date();
            ProductTimeStatus timestatus = new ProductTimeStatus();
            timestatus.setId(productOrderNew.getId());
            timestatus.setScProductOrderNo(productOrderNew.getScProductOrderNo());
            timestatus.setNodeFlowId(productOrderNew.getNodeFlowId());
            if(nodeFlow.getIsnaturalorworkday()==1) {//工作日
                Date nowDate = new Date();
                String orderEndTime = cmsService.findAfterDate(DateUtil.dateToString(nowDate,"yyyy-MM-dd HH:mm:ss"),nodeFlow.getManagementCycle())+" "+DateUtil.dateToString(nowDate,"HH:mm:ss");
                timestatus.setOrderEndTime(DateUtil.stringToDate(orderEndTime,"yyyy-MM-dd HH:mm:ss"));
            }else {
                try {
                    timestatus.setOrderEndTime(DateUtils.dateAddDayJs(new Date(), nodeFlow.getManagementCycle()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);
            timestatus.setDistributionStartTime(now);//计时开始时间
            timestatus.setDistributionTimeOutStatus(ScProductConstant.NORMAL);
            try {
                timestatus.setDistributionEndTime(DateUtils.dateAddDayJs(now, 1));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(productOrderNew.getFlowUserId() != null){
                timestatus.setReceiveStartTime(now);
                timestatus.setReceiveProcessTime(1);
                try {
                    timestatus.setReceiveEndTime(commonService.getWorkDateFrom(now,1));
                    timestatus.setReceiveTimeStatus(ScProductConstant.NORMAL);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            timestatus.setFlag(1);//必须要加入
            timestatus.setNodeTimeStatus(ScProductConstant.NORMAL);//写入节点超期状态,默认不超期
            timestatus.setOrderTimeStatus(ScProductConstant.NORMAL);
            this.saveOpt(timestatus,userEntity);
            timestatus.setCreaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            timestatus.setUpdaterOrgName(null == curentDept ? null : curentDept.get("name").toString());
            timestatus.setOrderStartTime(now);
            timestatus.setOrderProcessTime(nodeFlow.getManagementCycle());
            timestatus.setOrderProcessTimeType(nodeFlow.getIsnaturalorworkday());
            productTimeStatusDao.insertSelective(timestatus);

            try {
                if(null != productOrderNew && ScProductConstant.RZSCORDER_STATUS01.equals(productOrderNew.getStatus())&& productOrderNew.getFlowUserId() != null){
                    //推送消息到企业微信
                    String[] msgs = new String[]{productOrderNew.getScProductOrderNo(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")};
                    cmsService.sendMessage(productOrderNew.getFlowUserId(), 1L, msgs, MsgConstant.RZSC_SC_ALLOCATE, 1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 接入企大宝模板中心，返回流程信息
     * @param param
     * @return
     */
    public ProductNodeFlow getNodeFlow(Map<String, Object> param){
        Object resultStr = GateWayClientUtils.doPostJson(InitComponent.qdsApiUrl + "/qdstemplate/api/white/template_config/v1/search_template.do", param);
        logger.info(JSONObject.toJSONString(resultStr));
        //查询状态
        JSONObject result = JSONObject.parseObject(JSONObject.toJSONString(resultStr));
        //查询结果
        JSONArray records = result.getJSONArray("records");
        if (StringUtils.isEmpty(records)|| records.size()<1) {
            throw new CommonExcption("任务模板中未获取对应流程配置");
        }
        JSONObject record = records.getJSONObject(0);
        ProductNodeFlow nodeFlow = getProductNodeFlow(record);
        return nodeFlow;
    }



    /**
     * 获取企大宝任务模板任务转换成生产
     * @param record
     * @return
     */
    public ProductNodeFlow getProductNodeFlow(JSONObject record){
        ProductNodeFlow nodeFlow = new ProductNodeFlow();
        nodeFlow.setId(record.getLong("id"));
        nodeFlow.setVersion(0L);
        String cycleType = record.getString("cycleType");
        if("工作日".equals(cycleType)){
            nodeFlow.setIsnaturalorworkday(2);
        }else if("自然日".equals(cycleType)){
            nodeFlow.setIsnaturalorworkday(1);
        }else{
            throw new CommonExcption("不支持当前周期类型");
        }
        nodeFlow.setManagementCycle(record.getInteger("processingCycle"));
        return nodeFlow;
    }

    /**
     * 接入企大宝模板中心，根据流程ID返回节点信息
     * @param nodeFlow
     * @return
     */
    public List<ProductNode> getProductNode(ProductNodeFlow nodeFlow){
        Object resultStr = GateWayClientUtils.doGet(InitComponent.qdsApiUrl + "/qdstemplate/api/white/template_config/query_template.do?processId="+nodeFlow.getId());
        logger.info(JSONObject.toJSONString(resultStr));
        //查询状态
        JSONObject result = JSONObject.parseObject(JSONObject.toJSONString(resultStr));
        //查询结果
        JSONArray stageLawVOs = result.getJSONArray("stageLawVos");
        if(stageLawVOs.size() > 1){
            throw new CommonExcption("查询企大宝任务模板中流程失败，该任务模板包含多个阶段，请联系管理员调整！");
        }
        JSONObject stageLawVo = stageLawVOs.getJSONObject(0);
        logger.info(stageLawVo.toString());
        JSONArray taskLawVos = stageLawVo.getJSONArray("taskLawVos");
        JSONArray nodes = new JSONArray();
        for(int i = 0; i < taskLawVos.size(); i++){
            JSONObject jsonObject = taskLawVos.getJSONObject(i);
            JSONObject nodeObject = jsonObject.getJSONObject("templateTask");
            List<ProductNodeField> productNodeFields =JSONObject.parseArray(JSONObject.toJSONString(jsonObject.getJSONArray("templateRelationFields")),ProductNodeField.class);
            if(!CollectionUtils.isEmpty(productNodeFields)){
                List<Long> idList = productNodeFields.stream().map(ProductNodeField::getId).collect(Collectors.toList());
                List<String> nameList = productNodeFields.stream().map(ProductNodeField::getFieldName).collect(Collectors.toList());
                nodeObject.put("relationField", idList.stream().map(String::valueOf).collect(Collectors.joining(",")));
                nodeObject.put("relationFie",nameList.stream().map(String::valueOf).collect(Collectors.joining(",")));
            }
            nodes.add(nodeObject);
        }
        List<ProductNode> list = getProductNode(nodes);
        return list;
    }

    /**
     * 获取企大宝任务模板任务转换成生产节点
     * @param nodes
     * @return
     */
    public List<ProductNode> getProductNode(JSONArray nodes){
        List<ProductNode> nodeList = new ArrayList<>();
        for(int i=0; i<nodes.size(); i++){
            ProductNode node = new ProductNode();
            JSONObject jsonObject = nodes.getJSONObject(i);
            //周期类型
            String cycleType = jsonObject.getString("cycleType");
            if("WORK_DAY".equals(cycleType)){
                node.setIsNaturalorWorkday(1);
            }else if("NATURAL_DAY".equals(cycleType)){
                node.setIsNaturalorWorkday(2);
            }else{
                throw new CommonExcption("节点周期只能是工作日和自然日！");
            }
            //节点ID
            node.setId(jsonObject.getLong("id"));
            //排序
            node.setSort(jsonObject.getInteger("sort"));
            //佣金类型
            node.setCommission(jsonObject.getString("commission"));
            //佣金
            node.setBrokerage(jsonObject.getBigDecimal("brokerage"));
            //节点名称
            node.setName(jsonObject.getString("taskName"));
            //是否关键节点
            node.setIsKey(jsonObject.getInteger("isKeyTask"));
            //流程ID
            node.setProcessId(jsonObject.getLong("processId"));
            //办理周期
            node.setHandleDate(jsonObject.getInteger("processingCycle"));
            node.setRelationFieldIds(jsonObject.getString("relationField"));
            node.setRelationField(jsonObject.getString("relationFie"));
            nodeList.add(node);
        }
        return nodeList;
    }
    /**
     * 获取当前生产订单节点操作记录
     * @param params
     * @return
     */
    public List<Map<String, Object>> getProductOrderById(Map<String, Object> params) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        List<ProductNodeOperating> nodeList = productOrderDao.getProductOrderById(params);
        if(!CollectionUtils.isEmpty(nodeList)){
            for(ProductNodeOperating node :nodeList){
                Map<String, Object> map = new HashMap();
                map.put("nodeName",node.getNodeName());
                map.put("handlerName",node.getFlowUserName());
                map.put("latestOperateTime",node.getNodeOpetateTime());
                mapList.add(map);
            }
        }
        return mapList;
    }



    /**
     * 获取当前生产订单节点操作记录
     * @param params
     * @return
     */
    public List<TaskOperateRecord> getProductNodeById(Map<String, Object> params) {
        List<TaskOperateRecord> list = new ArrayList<>();
        List<ProductNodeOperating> nodeList = productOrderDao.getProductNodeById(params);
        if(!CollectionUtils.isEmpty(nodeList)){
            for(ProductNodeOperating node :nodeList){
                TaskOperateRecord taskOperateRecord = new TaskOperateRecord();
                taskOperateRecord.setScOrderId(String.valueOf(node.getScProductOrderId()));
                taskOperateRecord.setTaskId(String.valueOf(node.getNodeId()));
                taskOperateRecord.setNodeId(String.valueOf(node.getNodeId()));
                taskOperateRecord.setNodeName(node.getNodeName());
                taskOperateRecord.setTaskName(node.getNodeName());
                taskOperateRecord.setOperateTime(node.getNodeOpetateTime());
                taskOperateRecord.setOperaterName(node.getFlowUserName());
                taskOperateRecord.setRemarks(node.getRemark());
                list.add(taskOperateRecord);
            }
        }
        return list;
    }

    public Integer count(Map<String, Object> params) {
        List<ProductNodeOperating> nodeList = productOrderDao.getProductOrderById(params);
        return nodeList.size();
    }

    public List<ScOrderAndTaskDTO> getScOrderAndTask(Integer start, Integer limit, List<Long> scOrderIds) {
        List<ScOrderAndTaskDTO> result = new ArrayList<>();
        ScOrderAndTaskDTO scDto = new ScOrderAndTaskDTO();
        List<TaskListVo> taskList = new ArrayList<>();
        //获取生产信息
        PageList<TaskListVo> pageList = new PageList<>();

        List<ProductOrderDto> list = productOrderDao.selectByOrderIds(scOrderIds);
        for (ProductOrderDto dto : list){
            scDto.setScOrderId(dto.getId());
            scDto.setScOrderNo(dto.getScProductOrderNo());
            scDto.setStartTime(dto.getOrderTime());
            scDto.setFileId(dto.getCustomerId()+"-sc_product_order-orderFile-"+dto.getId());

            pageList.setPageSize(1);
            pageList.setCurrentPage(10);

            //节点信息为空
            if(StringUtils.isEmpty(dto.getNodeJson())){
                Map map = new HashMap(16);
                map.put("flowId",dto.getNodeFlowId());
                //根据流程id查询任务模板
                ProductNodeFlow flowInfo = productNodeFlowDao.queryFlowById(map);
                if(!StringUtils.isEmpty(flowInfo) && !StringUtils.isEmpty(flowInfo.getManagementCycle())){
                    //计算到期时间、是否已超期、超期时间
                    String orderEndTime;
                    if(flowInfo.getIsnaturalorworkday() == 1) {
                        Date nowDate = new Date();
                        orderEndTime = cmsService.findAfterDate(DateUtil.dateToString(nowDate,"yyyy-MM-dd HH:mm:ss"),flowInfo.getManagementCycle())+" "+DateUtil.dateToString(nowDate,"HH:mm:ss");
                        scDto.setDeadLine(DateUtil.stringToDate(orderEndTime,"yyyy-MM-dd HH:mm:ss"));
                    }else {
                        try {
                            scDto.setDeadLine(DateUtils.dateAddDayJs(new Date(), flowInfo.getManagementCycle()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                    if(!StringUtils.isEmpty(scDto.getDeadLine())){
                        if(System.currentTimeMillis() > scDto.getDeadLine().getTime()){
                            scDto.setIsOverdue("0");
                            scDto.setTaskOverTime(String.valueOf(System.currentTimeMillis() - scDto.getDeadLine().getTime()));
                        }else {
                            scDto.setIsOverdue("1");
                        }
                    }
                }
                //根据流程id查询节点信息表
                List<ProductNode>  nodeList = productNodeDao.queryByFlowId(map);
                pageList.setTotalCount(nodeList.size());
                for (ProductNode node : nodeList){
                    TaskListVo taskListVo = new TaskListVo();
                    taskListVo.setAnnexCount(0);
                    taskListVo.setBrokerage(null);
                    taskListVo.setStageName(null);
                    taskListVo.setTaskName(node.getName());
                    taskListVo.setId(String.valueOf(node.getId()));
                    taskListVo.setProductName(dto.getProductName());
                    taskListVo.setTaskId(String.valueOf(node.getId()));
                    taskListVo.setProductSpec(dto.getGoodsName());

                    Map m = new HashMap();
                    m.put("nodeId",node.getId());
                    m.put("scProductOrderId",dto.getId());
                    ProductNodeOperating operating = productNodeOperatingDao.selectByScOrderIdAndNodeId(m);
                    if(StringUtils.isEmpty(operating)){
                        taskListVo.setTaskSwitching("0");
                    }else{
                        taskListVo.setTaskSwitching("1");
                    }
                    //计算超期时间
                    //---------查询生产订单生产是否超期-----------
                    List<ProductTimeStatus> productTimeStatusList = productTimeStatusDao.query(new HashMap<String, Object>() {{
                        put("id", dto.getId());
                    }});
                    ProductTimeStatus productTimeStatus = new ProductTimeStatus();
                    if(productTimeStatusList != null  || productTimeStatusList.size() > 0){
                        productTimeStatus = productTimeStatusList.get(0);
                    }
                    //获取当前节点的配置的计算出的超期时间
                    Date currentDate = commonService.getDateFromStartByType(dto.getLatestEndNodeTime(),
                            node.getHandleDate(), productTimeStatus.getNodeSuspendMillisecond() == null ? 0 : productTimeStatus.getNodeSuspendMillisecond(),
                            node.getIsNaturalorWorkday());
                    if (currentDate.getTime() >= System.currentTimeMillis()) {
                        taskListVo.setIsOverdue("1");
                        taskListVo.setTaskOverTime("");
                    } else {
                        //超期
                        taskListVo.setIsOverdue("0");
                        Long overTime = Math.abs(currentDate.getTime() - System.currentTimeMillis());
                        taskListVo.setTaskOverTime(String.valueOf(overTime));
                    }
                    taskList.add(taskListVo);
                    pageList.setRecords(taskList);
                }
                scDto.setTaskListVos(pageList);

            }else{
                //不为空则获取任务节点信息
                ProductNodeFlow nodeFlow = new ProductNodeFlow();
                nodeFlow.setId(dto.getNodeFlowId());
                try {
                    List<ProductNode> nodes = this.getProductNode(nodeFlow);
                    pageList.setTotalCount(nodes.size());
                    for(ProductNode node : nodes){
                        TaskListVo taskListVo = new TaskListVo();
                        taskListVo.setAnnexCount(0);
                        taskListVo.setBrokerage(node.getBrokerage());
                        taskListVo.setStageName(null);
                        taskListVo.setTaskName(node.getName());
                        taskListVo.setId(String.valueOf(node.getId()));
                        taskListVo.setProductName(dto.getProductName());
                        taskListVo.setTaskId(String.valueOf(node.getId()));
                        taskListVo.setIsKeyTask(String.valueOf(node.getIsKey()));
                        Map m = new HashMap();
                        m.put("nodeId",node.getId());
                        m.put("scProductOrderId",dto.getId());
                        ProductNodeOperating operating = productNodeOperatingDao.selectByScOrderIdAndNodeId(m);
                        if(StringUtils.isEmpty(operating)){
                            //未完成
                            taskListVo.setTaskSwitching("0");
                        }else{
                            //已完成
                            taskListVo.setTaskSwitching("1");
                        }
                        taskList.add(taskListVo);
                        pageList.setRecords(taskList);
                    }
                    scDto.setTaskListVos(pageList);
                }catch (CommonExcption e){
                    e.getMessage();
                }
            }
            result.add(scDto);
        }
        return result;
    }


    public PageList<TaskOperateRecordDTO> getProductNodeOperating(Map params){
        Integer start = (Integer.parseInt(String.valueOf(params.get("start"))) - 1) * Integer.parseInt(String.valueOf(params.get("limit")));
        Integer length = Integer.parseInt(String.valueOf(params.get("limit")));
        params.put("scOrderId",Long.parseLong(String.valueOf(params.get("scOrderId"))));
        params.put("taskId",Long.parseLong(String.valueOf(params.get("taskId"))));
        Integer count = productNodeOperatingDao.selectByNodeIdCount(params);
        params.put("start",start);
        params.put("length",length);

        List<ProductNodeOperating> lists = productNodeOperatingDao.selectByNodeId(params);
        List<TaskOperateRecordDTO> resultList = new ArrayList();
        PageList<TaskOperateRecordDTO> pageList = new PageList<>();
        pageList.setTotalCount(count);
        pageList.setPageSize(1);
        pageList.setCurrentPage(10);
        for(ProductNodeOperating list : lists){
            TaskOperateRecordDTO dto = new TaskOperateRecordDTO();
            dto.setNodeId(String.valueOf(list.getNodeId()));
            dto.setNodeName(list.getNodeName());
            dto.setOperateName(list.getFlowUserName());
            dto.setOperateTime(list.getNodeOpetateTime());
            dto.setOperateType(list.getNodeProcessTimeType());
            dto.setRemarks(list.getRemark());
            dto.setScOrderId(String.valueOf(list.getScProductOrderId()));
            dto.setTaskId(String.valueOf(list.getId()));
            dto.setTaskName(list.getNodeName());
            resultList.add(dto);
        }
        pageList.setRecords(resultList);

        return pageList;
    }

    /**
     * 根据生产单id查询生产单的办理团队
     * @param scOrderId
     * @return
     */
    public List<Map> getScOrderManagementTeam(String scOrderId) {
        return productNodeOperatingDao.getScOrderManagementTeam(scOrderId);
    }
}
